import { CALC_INPUT, CALC_COMMIT, CALC_CLEAR } from "../constants/action-type";

const INITIAL_STATE = {
  expression: '',
  result: '',
}


export default function calculator(state = INITIAL_STATE, { type, payload }) {
  switch (type) {
    case CALC_INPUT:
      return {
        result: null,
        expression: state.expression + payload.toString(),
      };

    case CALC_COMMIT:
      try {
        const commitResult = eval(state.expression);
        return {
          ...state,
          result: commitResult,
        };
      } catch (e) {
        return {
          ...state,
          result: `Error(${e.message})`,
        }
      }     

    case CALC_CLEAR:
      return INITIAL_STATE;

    default:
      return state;
  }
}